import subprocess

# 定义要设置的内核参数及其值
kernel_params = {
    'vm.swappiness': 10,   #较低的值避免使用swap分区
    'vm.vfs_cache_pressure': 50, #调整内核回收文件系统缓存的速率
    'net.core.somaxconn': 1024,  #网络连接队列中可以挂起的最大连接数
    'net.ipv4.tcp_max_syn_backlog': 2048,  #TCP 连接的 SYN 队列的最大长度
    'net.ipv4.tcp_tw_reuse': 1,  #控制 TIME_WAIT 状态的 TCP 连接复用
    'net.ipv4.tcp_tw_recycle': 1,   #减少 TIME_WAIT 状态的连接数量
    'sysctl fs.file-max':100000,   #置系统可以打开的最大文件描述符数量
    'sysctl kernel.sched_min_granularity_ns':10000000,  #调整调度程序的时间片和调度延迟，优化多任务和高负载下的性能
    'sysctl kernel.sched_wakeup_granularity_ns':15000000,
}

def set_sysctl_param(param, value):
    """设置内核参数并检查结果"""
    try:
        # 使用 sysctl 命令设置参数
        subprocess.run(['sysctl', f'{param}={value}'], check=True, text=True)
        print(f'Successfully set {param} to {value}')
    except subprocess.CalledProcessError as e:
        print(f'Failed to set {param}: {e}')

def update_sysctl_conf(param, value):
    """更新 /etc/sysctl.conf 文件"""
    try:
        # 打开 /etc/sysctl.conf 文件进行更新
        with open('/etc/sysctl.conf', 'a') as conf_file:
            conf_file.write(f'{param}={value}\n')
        print(f'Added {param} to /etc/sysctl.conf')
    except IOError as e:
        print(f'Failed to update /etc/sysctl.conf: {e}')

def apply_sysctl_changes():
    """应用所有内核参数更改"""
    for param, value in kernel_params.items():
        set_sysctl_param(param, value)
        update_sysctl_conf(param, value)

    # 应用更改
    try:
        subprocess.run(['sysctl', '-p'], check=True, text=True)
        print('Applied changes from /etc/sysctl.conf')
    except subprocess.CalledProcessError as e:
        print(f'Failed to apply changes: {e}')

if __name__ == '__main__':
    apply_sysctl_changes()
